package csc.fresher.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import csc.fresher.commons.CurrencyRate;
import csc.fresher.currency.convertor.Currency;
import csc.fresher.view.SystemLoginManageBean;

/**
 * Servlet Filter implementation class FilterLogin
 */
@WebFilter("/saving-transaction/*")
public class FilterLogin implements Filter {

    /**
     * Default constructor. 
     */
    public FilterLogin() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//System.out.println(CurrencyRate.conversionRate(Currency.USD, Currency.VND));
		System.out.println("filter");
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        SystemLoginManageBean loginAdmin = (SystemLoginManageBean) req.getSession().getAttribute("systemLoginManageBean");
        String loginURL = req.getContextPath() + "/templates3/Logon.jsf";
        if(loginAdmin != null && loginAdmin.getSystemUser() != null){
        	if(loginAdmin.getRoles() == null || (!loginAdmin.getRoles().contains(new Long(3)) && !loginAdmin.getRoles().contains(new Long(4))))
        		res.sendRedirect(req.getContextPath() +"/templates3/UserManagement.jsf");
            chain.doFilter(req, res);
            System.err.println(loginAdmin != null);
        }
        else{
            res.sendRedirect(loginURL);
        }
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
